<?php
declare (strict_types=1);

namespace app\v1\controller;

use app\common\Express;
use app\Request;
use app\model\Goods;
use app\model\GoodsExpress;
use app\model\GoodsOrder;
use app\model\GoodsOrderAssess;
use app\model\GoodsOrderRefund;
use app\model\GoodsOrderService;
use app\model\User;
use app\model\UserAccount;
use think\db\Query;
use tool\Random;

class GoodsController
{

    protected $middleware = ['Login' => ['except' => ['orderDetail', 'getAccount', 'orderList']]];


    /**
     * 计算价格
     * @param int $goods_id
     * @param int $num
     * @return void
     */
    function getPrice(int $goods_id, int $num)
    {
        $goods = Goods::findOrFail($goods_id);
        $pay_amount = $num * $goods->price;
        writeJson(1, 'ok', $pay_amount);
    }

    /**
     * 创建订单
     * @param Request $request
     * @return void
     */
    function createOrder(Request $request)
    {
        $address_id = $request->post('address_id/d');
        $goods_id = $request->post('goods_id/d');
        $mark = $request->post('mark', '');
        $num = $request->post('num/d');
        $proof = $request->post('proof', ''); //支付凭证
        $invite_code = $request->post('invite_code', '');
        $spec_id = $request->post('spec_id');

        if (!$num || !$address_id || !$spec_id) {
            writeJson(0, '参数错误');
        }
        $goods = Goods::findOrFail($goods_id);
        if ($num > $goods->sku) {
            writeJson(0, '库存不足');
        }
        if (empty($invite_code)) {
            $seller = User::findOrFail($request->user_id);
            $flow = 0;
        } else {
            $seller = User::where(['invite_code' => $invite_code])->findOrFail();
            $flow = 1;
        }
        if ($seller->level == 0) {
            writeJson(0, '身份错误');
        }

        $pay_amount = $num * $goods->price;
        $hand_price = $goods->price - $goods->{'level_' . $seller->level};
        $hand_amount = $hand_price * $num;
        $profit_amount = $pay_amount - $hand_amount;
        $data = [
            'user_id' => $request->user_id,
            'seller_id' => $seller->id,
            'spec_id' => $spec_id,
            'address_id' => $address_id,
            'goods_id' => $goods_id,
            'num' => $num,
            'pay_amount' => $pay_amount,
            'mark' => $mark,
            'proof' => $proof,
            'order_no' => Random::getOrderNumber(),
            'hand_amount' => $hand_amount,
            'profit_amount' => $profit_amount,
            'flow' => $flow
        ];

        $ret = GoodsOrder::create($data);
        writeJson(1, 'ok', $ret);
    }

    /**
     * 订单列表
     * @return void
     */
    function orderList(Request $request, int $status)
    {

        $rows = GoodsOrder::with(['spec', 'goods', 'seller'])
            ->where(['user_id' => $request->user_id])
            ->when(in_array($status, [1, 2, 3, 4]), function (Query $query) use ($status) {
                switch ($status) {
                    case 1:
                        $query->where('status', 1);
                        break;
                    case 2:
                        $query->where('status', 2);
                        break;
                    case 3:
                        $query->whereIn('status', [3, 4]);
                        break;
                    case 4:
                        $query->whereIn('status', [6, 7, 8, 9, 10, 11]);
                        break;
                }
            })
            ->order(['id' => 'desc'])
            ->paginate()
            ->items();
        writeJson($rows);
    }

    /**
     * 订单详情
     * @param int $id
     * @return void
     */
    function orderDetail(int $id)
    {
        $row = GoodsOrder::with([
            'goods',
            'seller',
            'address' => function (Query $query) {
                $query->withTrashed();
            },
            'service',
            'spec',
            'express'])->findOrFail($id);
        writeJson($row);
    }

    /**
     * 取消订单
     * @return void
     */
    function orderCancel(Request $request)
    {
        $id = $request->post('id/d');
        $account_id = $request->post('account_id/d');
        $row = GoodsOrder::findOrFail($id);
        if (!in_array($row->status, [0, 1])) {
            writeJson(0, '订单异常');
        }
        if ($row->status == 1) {
            //执行退款
            $account = UserAccount::where(['user_id' => $request->user_id])->findOrFail($account_id);
            GoodsOrderRefund::create([
                'user_id' => $request->user_id,
                'order_id' => $row->id,
                'refund_amount' => $row->pay_amount,
                'account_id' => $account->id,
            ]);
        }
        $row->status = 5;
        $row->save();
        writeJson();
    }

    /**
     * 获取收款方式
     * @return void
     */
    function getAccount(string $invite_code, int $id)
    {

        $user = User::where(['invite_code' => $invite_code])->find();
        $goods = Goods::where(['id' => $id])->find();
        if ($user) {
            $data = $user->account;
        } else {
            $data = $goods->account_json;
        }
        writeJson($data);

    }

    /**
     * 获取评价数量
     * @param Request $request
     * @return void
     */
    function getGoodsAssessCount(Request $request)
    {
        $id = $request->get('id/d');
        $data = [
            'assess_count' => GoodsOrderAssess::where(['goods_id' => $id])->select(),
            'assess_good_count' => GoodsOrderAssess::where(['goods_id' => $id])->where(['score' => 5])->select(),
            'assess_normal_count' => GoodsOrderAssess::where(['goods_id' => $id])->whereIn('score', [3, 4])->select(),
            'assess_bad_count' => GoodsOrderAssess::where(['goods_id' => $id])->whereIn('score', [1, 2])->select(),
            'assess_images_count' => GoodsOrderAssess::where(['goods_id' => $id])->where('images', '<>', '')->select(),
        ];
        writeJson($data);
    }

    /**
     * 获取评价列表
     * @param Request $request
     * @return void
     */
    function getGoodsAssess(Request $request)
    {
        $id = $request->get('id/d');
        $rows = GoodsOrderAssess::where(['goods_id' => $id])
            ->with(['user', 'orders.spec'])
            ->paginate()
            ->items();
        writeJson($rows);
    }

    /**
     * 确认收货
     * @return void
     */
    function orderConfirm(Request $request)
    {
        $id = $request->post('id/d');
        $row = GoodsOrder::findOrFail($id);
        if ($row->status != 2) {
            writeJson(0, '订单异常');
        }
        $row->status = 3; //待评价
        $row->save();
        writeJson();
    }

    /**
     * 订单评价
     * @return void
     */
    function orderAssess(Request $request)
    {
        $id = $request->post('id/d');
        $score = $request->post('score/d');
        $images = $request->post('images');
        $content = $request->post('content');
        $anonym = $request->post('anonym/d');
        $row = GoodsOrder::where(['user_id' => $request->user_id])->findOrFail($id);
        if ($row->status != 3) {
            writeJson(0, '订单异常');
        }
        $row->status = 4;
        $row->save();
        //评论
        GoodsOrderAssess::create([
            'order_id' => $id,
            'goods_id' => $row->goods->id,
            'user_id' => $request->user_id,
            'score' => $score,
            'images' => $images,
            'content' => $content,
            'anonym' => $anonym,
        ]);
        writeJson();
    }

    /**
     * 订单售后
     * @param Request $request
     * @return void
     */
    function orderService(Request $request)
    {
        $id = $request->post('id/d');
        $type_text = $request->post('type_text');
        $take_text = $request->post('take_text');
        $reason_text = $request->post('reason_text');
        $images = $request->post('images', '');
        $mobile = $request->post('mobile', '');
        $content = $request->post('content', '');
        $amount = $request->post('amount');
        $row = GoodsOrder::where(['user_id' => $request->user_id])->findOrFail($id);
        if (!in_array($row->status, [2, 3, 4])) {
            writeJson(0, '订单异常');
        }
        if ($amount > $row->pay_amount) {
            writeJson(0, '退款金额不能大于订单金额');
        }
        $row->status = 6;
        $row->save();
        GoodsOrderService::create([
            'user_id' => $request->user_id,
            'order_id' => $id,
            'type_text' => $type_text,
            'take_text' => $take_text,
            'reason_text' => $reason_text,
            'images' => $images,
            'mobile' => $mobile,
            'content' => $content,
            'amount' => $amount,
        ]);
        writeJson();
    }

    /**
     * 取消售后
     * @param Request $request
     * @return void
     */
    function orderServiceCancel(Request $request)
    {
        $id = $request->post('id/d');
        $row = GoodsOrder::where(['user_id' => $request->user_id])->findOrFail($id);
        if (!in_array($row->status, [6, 7])) {
            writeJson(0, '订单异常');
        }
        $row->status = 10;
        $row->service->status = 3;
        $row->together(['service'])->save();
        writeJson();
    }


    /**
     * 退货
     * @param Request $request
     * @return void
     */
    function orderServiceReturn(Request $request)
    {
        $id = $request->post('id/d');
        $account_id = $request->post('account_id/d');
        $express_id = $request->post('express_id/d');
        $waybill = $request->post('waybill');
        $account = UserAccount::where(['user_id' => $request->user_id])->findOrFail($account_id);
        $row = GoodsOrderService::where(['order_id' => $id])->findOrFail();
        if ($row->status != 1) {
            writeJson(0, '订单异常');
        }
        $row->express_id = $express_id;
        $row->waybill = $waybill;
        $row->account_id = $account->id;
        $row->goods_order->status = 8;
        $row->together(['goods_order'])->save();
        writeJson();
    }

    /**
     * 快递公司
     * @return void
     */
    function express()
    {
        $rows = GoodsExpress::order(['weigh' => 'desc'])->select();
        writeJson($rows);
    }

    /**
     * 获取快递信息
     * @param Request $request
     * @return void
     */
    function getExpressInfo(Request $request)
    {
        $id = $request->get('id/d');
        $row = GoodsOrder::where(['user_id' => $request->user_id])->findOrFail($id);
        if (in_array($row->status, [0, 1])) {
            writeJson(0, '暂无快递信息');
        }
        $ret = Express::getExpressInfo($row->express->code, $row->waybill);
        $ret = json_decode($ret);
        if (isset($ret->result)) {
            writeJson(0, $ret->message);
        }
        writeJson($ret->data);
    }


}
